﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.IO;

namespace KataProfiler
{
    public partial class Form1 : Form
    {
        static ASCIIEncoding encoding = new ASCIIEncoding();

        public Form1()
        {
            InitializeComponent();
        }

        const string HOST = "localhost";
        const int PORT_NUMBER = 38300;
        const int BUFFER_SIZE = 1024 * 1024;

        private static byte[] m_sbuffer = new byte[BUFFER_SIZE];

        private void button1_Click(object sender, EventArgs e)
        {
            richTextBox1.Text = "";

            doCapture();
        }

        private void doCapture()
        {
            TcpClient client = new TcpClient();
            client.Connect(HOST, PORT_NUMBER);
            Stream stream = client.GetStream();

            bool finish = false;

            int ccc = 0;

            KPMessage p = null;

            while (!finish)
            {
                ccc++;

                int len = 0;
                try
                {
                    len = stream.Read(m_sbuffer, 0, BUFFER_SIZE);
                }
                catch (Exception)
                {
                    len = 0;
                }

                if (len <= 0) continue;

                int offset = 0;
                int ddd = 0;
                
                while (true)
                {
                    ddd++;
                    if (p == null) p = new KPMessage();
                    int k = p.consume(m_sbuffer, offset, len - 1);
                    if (p.isFull())
                    {
                        if (p.isFinishCaptureMessage())
                        {
                            finish = true;
                            break;
                        }
                        receiveMessage(p);
                        p = null;
                    }
                    offset += k;
                    Utils.assert(offset <= len);
                    if (offset == len) break;
                }
            }

            stream.Close();
            client.Close();
        }

        private void receiveMessage(KPMessage msg)
        {
            string str = msg.m_length > 0 ? encoding.GetString(msg.m_pData, 0, msg.m_length) : "";
            richTextBox1.Text += ((KPMessage.KPMessageType)msg.m_type).ToString() + " " + str + "\n";
        }

        private void Form1_Load(object sender, EventArgs e)
        {
        }
    }
}
